package com.sky.service.userImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 1、获取包含OpenId的JSON字符串
        String  result = getOpenId(userLoginDTO.getCode());
        // 2、解析字符串，获取OpenId

        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        // 3、如果没有openid,登录失败
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 4、查询openid，获取用户信息
        User user = userMapper.getByOpenId(openid);
        // 5、没有用户信息即新用户,自动完成注册
        if (user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 6、返回用户信息
        return user;
    }

    /**
     * 利用HttpClient构造请求访问微信接口服务
     * @param code-用户登录凭证
     * @return JSON字符串-返回包含用户标识openId的JSON字符串
     */
    private String getOpenId(String code){
        HashMap<String, String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        return HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
    }
}
